package com.smsc.headend.task.engine.handler.impl.deviceconfig;

import cn.hutool.core.convert.Convert;
import com.smsc.headend.common.enums.errorcode.TaskHandlerErrorCode;
import com.smsc.headend.common.utils.CosemUtils;
import com.smsc.headend.module.data.enums.OperationGroup;
import com.smsc.headend.module.data.enums.OperationName;
import com.smsc.headend.module.protocol.DeviceData;
import com.smsc.headend.module.protocol.cosem.bo.CosemData;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.exception.UDISTaskHandlerException;
import com.smsc.headend.task.engine.handler.TaskHandler;
import com.smsc.headend.task.engine.service.CosemXmlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @ClassName ReadClockObjectHandler
 * @Description
 * @Author
 * @Date 2021/11/23 8:43
 */
@Slf4j
public class ReadDisplayCodeHandler implements TaskHandler {

    @Autowired
    CosemXmlService cosemXmlService;
    @Autowired
    TaskDAO taskDAO;

    @Override
    public int handle(Task task, AtomicTask atomicTask, DeviceData deviceData, String actionResult) throws UDISTaskHandlerException {
        if (deviceData instanceof CosemData == false) {
            throw new UDISTaskHandlerException(TaskHandlerErrorCode.DEVICE_DATA_TYPE_NOT_SUPPORT.toString());
        }

        CosemData cosemData = (CosemData) deviceData;
        Object data = cosemXmlService.getData(cosemData.getType(), cosemData.getValue());

        long expireSeconds = 600;

        OperationName operationName = OperationName.forId(atomicTask.getOperationId());


        if (isSubTaskGroupLastAtomicTask(task, atomicTask)) {
            taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), "subTaskCompleted", true, expireSeconds, true);
        }

        return 1;
    }

    @Override
    public int handleFailure(Task task, AtomicTask atomicTask, String message) {
        log.info("error {}", message);

        if (atomicTask.getGroupId() == OperationGroup.GetClock.getId().intValue()) {
            if (task.getIsODR()) {
                String stepOperationName = OperationName.forId(atomicTask.getOperationId()).getName();
                String result = String.format("step %s failed, [%s]", stepOperationName, message);
                taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), stepOperationName, result, 3600L, false);
            }
        }

        return -1;
    }

}
